﻿using AutoMapper;
using ProjectManageSystemApi.DbEntity;
using ProjectManageSystemApi.Enums;
using ProjectManageSystemApi.Models.UserCheckDetailModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ProjectManageSystemApi.Services.Impl
{
    public class UserCheckDetailServices : IUserCheckDetailServices
    {
        readonly IFreeSql _fsql;
        readonly IMapper _mapper;
        public UserCheckDetailServices(IFreeSql fsql, IMapper mapper)
        {
            _fsql = fsql;
            _mapper = mapper;
        }

        public bool Add(AddUserCheckDetailDto detail)
        {
            var data = _mapper.Map<AddUserCheckDetailDto, UserCheckDetail>(detail);
            data.Status = (byte)UserCheckDetailStatus.Exist;
            return _fsql.Insert(data).ExecuteAffrows() > 0;
        }
        public bool Update(AddUserCheckDetailDto detail)
        {
            var data = _mapper.Map<AddUserCheckDetailDto, UserCheckDetail>(detail);
            return _fsql.Update<UserCheckDetail>().SetSource(data).IgnoreColumns(x => new { x.Status, x.UserCheckId }).ExecuteAffrows() > 0;
        }
        public bool Delete(uint id) 
        {
            return _fsql.Delete<UserCheckDetail>().Where(x=>x.Id == id).ExecuteAffrows() > 0;
            // return _fsql.Update<UserCheckDetail>(id).Set(x => x.Status, (byte)UserCheckDetailStatus.Delete).ExecuteAffrows() > 0;
        }


        public List<UserCheckDetailDto> QueryByUserIdAndBelongsDate(long userId, DateTime belongsDate) 
        {
            var datas = _fsql.Select<UserCheckDetail>()
                .Include(x=>x.WorkerTypeInfo)
                .Where(x=>x.Status < (byte)UserCheckDetailStatus.Delete)
                .Where(x=> _fsql.Select<UserCheckInfo>()
                    .Where(i=> i.Id == x.UserCheckId)
                    .Any(i => i.UserId == userId && i.BelongsDate == belongsDate.Date))
                .ToList();
            return _mapper.Map<List<UserCheckDetail>, List<UserCheckDetailDto>>(datas);
        }
        public bool HasExistId(uint id)
        {
            return _fsql.Select<UserCheckDetail>().Any(x => x.Id == id && x.Status == (byte)UserCheckDetailStatus.Exist);
        }
    }
}
